// 创建 state 对象 
// 根据 state 来 渲染dom
// state 变化 
// 再次根据 state 来渲染dom

class Component {

    createElementByDomString (domStr) {
        let domElement = document.createElement('div')
        domElement.innerHTML = domStr
        this.domElement = domElement.children[0] 
        this.domElement.component = this
        return this.domElement
    }

    setState (partcialState) {
        this.state = Object.assign(this.state, partcialState)
        let oldElement = this.domElement
        let newElement = this.renderToDom()
        oldElement.parentElement.replaceChild(newElement, oldElement)
    }

    renderToDom () {
        return this.createElementByDomString(this.render())
    }

    mount (container) {
        container.appendChild(this.renderToDom())
    }


}

window.trigger = function(e, type) {
    console.log(e)
    e.target.component[type].call(e.target.component)
}

class Counter extends Component {
    constructor() {
        super()
        this.state = {
            number: 0
        }
    }

    add () {
        const { number } = this.state
        this.setState({number: number + 1})
    }

    render () {
        const { number } = this.state
        return  `<button onclick="trigger(event, 'add')"> ${number}</button>`
    }
}

